#!/bin/bash

# Qt 6 环境配置脚本
# 用于配置 Qt 6.x 开发和编译环境

echo "=== Qt 6 环境配置脚本 ==="
echo ""

# 检查 Qt 6 是否已安装
if ! brew list qt &>/dev/null; then
    echo "❌ Qt 6 未安装，正在安装..."
    brew install qt
else
    QT_VERSION=$(brew list --versions qt | awk '{print $2}')
    echo "✅ Qt 6 已安装: $QT_VERSION"
fi

# 获取 Qt 安装路径
QT_PATH=$(brew --prefix qt)
echo "📁 Qt 安装路径: $QT_PATH"

# 配置环境变量
echo ""
echo "=== 环境变量配置 ==="
echo "请将以下内容添加到您的 ~/.zshrc 或 ~/.bash_profile 文件中："
echo ""
echo "# Qt 6 环境配置"
echo "export QT_DIR=\"$QT_PATH\""
echo "export Qt6_DIR=\"$QT_PATH\""
echo "export PATH=\"$QT_PATH/bin:\$PATH\""
echo "export PKG_CONFIG_PATH=\"$QT_PATH/lib/pkgconfig:\$PKG_CONFIG_PATH\""
echo "export CMAKE_PREFIX_PATH=\"$QT_PATH:\$CMAKE_PREFIX_PATH\""
echo ""

# 检查重要的 Qt 工具
echo "=== Qt 工具检查 ==="
if [ -f "$QT_PATH/bin/qmake" ]; then
    echo "✅ qmake: $QT_PATH/bin/qmake"
    "$QT_PATH/bin/qmake" -v
else
    echo "❌ qmake 未找到"
fi

if [ -f "$QT_PATH/bin/macdeployqt" ]; then
    echo "✅ macdeployqt: $QT_PATH/bin/macdeployqt"
else
    echo "❌ macdeployqt 未找到"
fi

if [ -f "$QT_PATH/bin/moc" ]; then
    echo "✅ moc: $QT_PATH/bin/moc"
else
    echo "❌ moc 未找到"
fi

# 显示可用的 Qt 模块
echo ""
echo "=== Qt 模块 ==="
ls -1 "$QT_PATH/lib" | grep -E "Qt6.*\.framework$|libQt6.*\.dylib$" | head -20

# 提供自动配置选项
echo ""
echo "=== 自动配置 ==="
read -p "是否自动添加环境变量到 ~/.zshrc? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    # 备份现有配置
    if [ -f ~/.zshrc ]; then
        cp ~/.zshrc ~/.zshrc.backup_$(date +%Y%m%d_%H%M%S)
        echo "✅ 已备份 ~/.zshrc"
    fi
    
    # 添加 Qt 6 配置
    cat >> ~/.zshrc << EOF

# Qt 6 环境配置 (自动添加于 $(date))
export QT_DIR="$QT_PATH"
export Qt6_DIR="$QT_PATH"
export PATH="$QT_PATH/bin:\$PATH"
export PKG_CONFIG_PATH="$QT_PATH/lib/pkgconfig:\$PKG_CONFIG_PATH"
export CMAKE_PREFIX_PATH="$QT_PATH:\$CMAKE_PREFIX_PATH"
EOF
    
    echo "✅ 环境变量已添加到 ~/.zshrc"
    echo "请运行 'source ~/.zshrc' 或重新打开终端使配置生效"
fi

echo ""
echo "=== 完成 ==="
echo "Qt 6 开发环境配置完成！"
